//
//  MyClinicTabController.m
//  EcmDoctor
//
//  Created by 张进 on 15/7/7.
//  Copyright (c) 2015年 张进. All rights reserved.
//

#import "MyClinicTabController.h"
#import "AppUtils.h"
#import "QuestionOnlineController.h"
#import "QuestionTelController.h"
#import "QuestionOnlineDetailController.h"
#import "QuestionTelDetailController.h"
#import "ClinicDetailViewController.h"
#import "TreatmentsViewController.h"
#import "AppDelegate.h"
#import "badgeUrl.h"

@interface MyClinicTabController (){
    BOOL _isCardView;
    NSMutableArray *tableData;  //表格数据
    int i;//记录前一个选中页面的下标值
}

@end

@implementation MyClinicTabController

- (void)viewDidLoad {
    [super viewDidLoad];
    i = 0;
    // Do any additional setup after loading the view.
    
    [self.tabBar setBackgroundImage:[self createImageWithColor:[UIColor clearColor]]];
    [self.tabBar setShadowImage:[self createImageWithColor:[UIColor clearColor]]];
    
    CGFloat navHeight = self.navigationController.navigationBar.frame.size.height;
    CGFloat navY = self.navigationController.navigationBar.frame.origin.y;
    CGRect rect = self.tabBar.frame;
    CGFloat barHeight = rect.size.height;
    rect.origin.y = navHeight+barHeight+navY;
    rect.size.height = 49;
    self.tabBar.frame = rect;

    tableData = [[NSMutableArray alloc] init];
    
    //自定义tab bar item样式
    
    NSArray *items = self.tabBar.items;
    
    //添加badge
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    [self.view addSubview:app.onLineBadge];
    [self.view addSubview:app.telBadge];
    [self.view addSubview:app.clinicBadge];
    
    [self upDateBadgemethod:@"getOnLineInfoNum"];
    [self upDateBadgemethod:@"getOnPhoneInfoNum"];
    [self upDateBadgemethod:@"getOnAddTimeInfoNum"];
    
    
    //在线咨询
    UITabBarItem *onlineItem = [items objectAtIndex:0];
    onlineItem.image = [[UIImage imageNamed:@"在线咨询"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    onlineItem.selectedImage =[[UIImage imageNamed:@"在线咨询_press"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    onlineItem.title = nil;
    //电话咨询
    UITabBarItem *telItem = [items objectAtIndex:1];
    telItem.image = [[UIImage imageNamed:@"电话咨询"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    telItem.selectedImage =[[UIImage imageNamed:@"电话咨询_press"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    telItem.title = nil;
    //门诊加号
    UITabBarItem *menzhenItem = [items objectAtIndex:2];
    menzhenItem.image = [[UIImage imageNamed:@"门诊加号"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    menzhenItem.selectedImage =[[UIImage imageNamed:@"门诊加号_press"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    menzhenItem.title = nil;

    [self.tabBar setBackgroundImage:[[UIImage imageNamed:@"clinic_tabbg1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
//    NSLog(@"imgHeight:%f;tabBarHeight:%f",menzhenItem.image.size.height,self.tabBar.frame.size.height);
    self.delegate = self;
    
    //初始为card布局
    _isCardView = YES;
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showQuestionRelyDetail"]) {
        QuestionOnlineDetailController *detail = [segue destinationViewController];
        // 对详情页面赋值
        detail.voiceUrl = sender[@"voice"];
        detail.detail = sender[@"content"];
        detail.name = sender[@"name"];
        detail.sex = sender[@"sex"];
        detail.age = [NSString stringWithFormat:@"%@", sender[@"age"]];
        detail.imageUrl = sender[@"picUrl"];
        detail.headImageUrl = sender[@"headImage"];
        detail.doctorId = sender[@"doctorId"];
        detail.askId = sender[@"askId"];
        detail.ifDownload = 4;
        
    } else if ([segue.identifier isEqualToString:@"showQuestionNoRelyDetail"]) {
        QuestionTelDetailController *detail = [segue destinationViewController];
        // 对详情页面赋值
        detail.voiceUrl = sender[@"voice"];
        detail.detail = sender[@"content"];
        detail.name = sender[@"name"];
        detail.sex = sender[@"sex"];
        detail.age = [NSString stringWithFormat:@"%@", sender[@"age"]];
        detail.imageUrl = sender[@"picUrl"];
        detail.headImageUrl = sender[@"headImage"];
        detail.infoStr = sender[@"info"];
        detail.doctorId = sender[@"doctorId"];
        detail.askId = sender[@"askId"];
        detail.ifDownload = 4;
        
    } else if ([segue.identifier isEqualToString:@"showClinicContrillerDetail"]) {
        
        ClinicDetailViewController *clinic = [segue destinationViewController];
        clinic.detail = sender[@"content"];
        clinic.name = sender[@"name"];
        clinic.sex = sender[@"sex"];
        clinic.age = [NSString stringWithFormat:@"%@", sender[@"age"]];
        clinic.imageUrl = sender[@"picUrl"];
        clinic.headImageUrl = sender[@"headImage"];
        clinic.voiceUrl = sender[@"voiceUrl"];
        clinic.infoStr = sender[@"info"];
        clinic.doctorId = sender[@"doctorId"];
        clinic.askId = sender[@"askId"];
        clinic.ifDownload = 4;
        
    }
}


//implement
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    
    //切换bar背景图片,以显示选中状态
    if ([viewController isEqual:[tabBarController.viewControllers objectAtIndex:0]]) {
        if ([tabBarController.viewControllers objectAtIndex:1].view != nil) {
            [tabBarController.viewControllers objectAtIndex:1].view = nil;
        }
        
        if ([tabBarController.viewControllers objectAtIndex:2].view != nil) {
            [tabBarController.viewControllers objectAtIndex:2].view = nil;
        }
        
        //改变tabbar图片
        [self.tabBar setBackgroundImage:[[UIImage imageNamed:@"clinic_tabbg1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }else if([viewController isEqual:[tabBarController.viewControllers objectAtIndex:1]]){
        if ([tabBarController.viewControllers objectAtIndex:0].view != nil) {
            [tabBarController.viewControllers objectAtIndex:0].view = nil;
        }
        
        if ([tabBarController.viewControllers objectAtIndex:2].view != nil) {
            [tabBarController.viewControllers objectAtIndex:2].view = nil;
        }
        
        //改变tabbar图片
        [self.tabBar setBackgroundImage:[[UIImage imageNamed:@"clinic_tabbg2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }else{
        if ([tabBarController.viewControllers objectAtIndex:1].view != nil) {
            [tabBarController.viewControllers objectAtIndex:1].view = nil;
        }
        
        if ([tabBarController.viewControllers objectAtIndex:0].view != nil) {
            [tabBarController.viewControllers objectAtIndex:0].view = nil;
        }
        //改变tabbar图片
        [self.tabBar setBackgroundImage:[[UIImage imageNamed:@"clinic_tabbg3"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    //若当前点击的barbuttonitem就是选中的item，则不做任何操作，否则切换；屏蔽重新加载viewcontroller的问题
    if (([viewController isEqual:[tabBarController.viewControllers objectAtIndex:0]] && tabBarController.selectedIndex == 0)
        || ([viewController isEqual:[tabBarController.viewControllers objectAtIndex:1]] && tabBarController.selectedIndex == 1)
        || ([viewController isEqual:[tabBarController.viewControllers objectAtIndex:2]] && tabBarController.selectedIndex == 2)) {
        return NO;
    }else{
        return YES;
    }
}

- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
// Called when the view is about to made visible. Default does nothing
- (void)viewWillAppear:(BOOL)animated{
//    self.navigationController.navigationBar.translucent = YES;
//    self.automaticallyAdjustsScrollViewInsets = NO;
    //右上角切换视图按钮
    UIImage *tableIcon = [UIImage imageNamed:@"bg_titleschange_normal"];
    CGFloat barHeight = self.tabBarController.navigationController.navigationBar.frame.size.height;
    tableIcon = [AppUtils scaleImage:tableIcon ToSize:CGSizeMake(barHeight*0.45, barHeight*0.45)];
    
    self.tabBarController.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeCardView:)];
    
    
    self.tabBarController.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];

}

// Called when the view has been fully transitioned onto the screen. Default does nothing
- (void)viewDidAppear:(BOOL)animated{
    
}

-(void)enableBarButtonItem:(UIBarButtonItem *)item{
    item.action = @selector(changeCardView:);
}

-(void)changeCardView:(id)sender{
    
    if (_isCardView) {
        UIImage *cardIcon = [UIImage imageNamed:@"bg_titleschange_press"];
        CGFloat barHeight = self.tabBarController.navigationController.navigationBar.frame.size.height;
        cardIcon = [AppUtils scaleImage:cardIcon ToSize:CGSizeMake(barHeight*0.45, barHeight*0.45)];
        
        self.tabBarController.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithImage:cardIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeCardView:)];
        
        self.tabBarController.navigationItem.rightBarButtonItem.tintColor = [UIColor clearColor];
        self.tabBarController.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithPatternImage:cardIcon];
        
        self.tabBarController.navigationItem.rightBarButtonItem.action = nil;
        [self performSelector:@selector(enableBarButtonItem:) withObject:self.tabBarController.navigationItem.rightBarButtonItem afterDelay:0.3];
        
        //翻转动画
        CATransition *animation = [CATransition animation];
        [animation setDuration:0.4];
        [animation setType: @"oglFlip"];
        
        [animation setSubtype: kCATransitionFromRight];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
        
        //在线咨询
        UINavigationController *c1 = [self.viewControllers objectAtIndex:0];
        UIViewController *onlineCardController = [c1.viewControllers objectAtIndex:0];
        [c1.view.layer removeAllAnimations];
        [c1.view.layer addAnimation:animation forKey:nil];
        
        [onlineCardController performSegueWithIdentifier:@"onlineToTableId" sender:self];
        //电话问诊
        UINavigationController *c2 = [self.viewControllers objectAtIndex:1];
        UIViewController *telController = [c2.viewControllers objectAtIndex:0];
        [c2.view.layer removeAllAnimations];
        [c2.view.layer addAnimation:animation forKey:nil];
        
        [telController performSegueWithIdentifier:@"onlineToTableId" sender:self];
        
        //门诊加号
        UINavigationController *c3 = [self.viewControllers objectAtIndex:2];
        UIViewController *clinicCardController = [c3.viewControllers objectAtIndex:0];
        [c3.view.layer removeAllAnimations];
        [c3.view.layer addAnimation:animation forKey:nil];
        
        [clinicCardController performSegueWithIdentifier:@"onlineToTableId" sender:self];
        
    }else{
        UIImage *tableIcon = [UIImage imageNamed:@"bg_titleschange_normal"];
        CGFloat barHeight = self.tabBarController.navigationController.navigationBar.frame.size.height;
        tableIcon = [AppUtils scaleImage:tableIcon ToSize:CGSizeMake(barHeight*0.45, barHeight*0.45)];
        
        self.tabBarController.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeCardView:)];
        
        self.tabBarController.navigationItem.rightBarButtonItem.tintColor = [UIColor clearColor];
        self.tabBarController.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
        
        self.tabBarController.navigationItem.rightBarButtonItem.action = nil;
        [self performSelector:@selector(enableBarButtonItem:) withObject:self.tabBarController.navigationItem.rightBarButtonItem afterDelay:0.3];
        
        //动画
        CATransition *animation = [CATransition animation];
        [animation setDuration:0.4];
        [animation setType: @"oglFlip"];
        
        [animation setSubtype: kCATransitionFromLeft];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
        
        //在线咨询
        UINavigationController *c1 = [self.viewControllers objectAtIndex:0];
        [c1.view.layer removeAllAnimations];
        [c1.view.layer addAnimation:animation forKey:nil];
        
        [c1 popToRootViewControllerAnimated:YES];
        //在线咨询
        UINavigationController *c2 = [self.viewControllers objectAtIndex:1];
        [c2.view.layer removeAllAnimations];
        [c2.view.layer addAnimation:animation forKey:nil];
        
        [c2 popToRootViewControllerAnimated:YES];
        
        //门诊加号
        UINavigationController *c3 = [self.viewControllers objectAtIndex:2];
        [c3.view.layer removeAllAnimations];
        [c3.view.layer addAnimation:animation forKey:nil];
        
        [c3 popToRootViewControllerAnimated:YES];
    }
    _isCardView = !_isCardView;
}

#pragma mark 更新badge值
- (void)upDateBadgemethod:(NSString *)method{
    NSString *docId = [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
    [badgeUrl badgeWithdoctor_info_id:docId moduleName:@"DoctorRS" methodname:method success:^(NSString *badgeNumber) {
        AppDelegate *app = [UIApplication sharedApplication].delegate;

        if ([method isEqualToString:@"getOnLineInfoNum"]) {
            app.onLineBadge.text = badgeNumber;
            if ([badgeNumber isEqualToString:@"0"]) {
                app.onLineBadge.alpha = 0;
            }
        } else if ([method isEqualToString:@"getOnPhoneInfoNum"]) {
            app.telBadge.text = badgeNumber;
            if ([badgeNumber isEqualToString:@"0"]) {
                app.telBadge.alpha = 0;
            }
        } else if ([method isEqualToString:@"getOnAddTimeInfoNum"]) {
            app.clinicBadge.text = badgeNumber;
            if ([badgeNumber isEqualToString:@"0"]) {
                app.clinicBadge.alpha = 0;
            }
        }
        
    } failure:^(NSError *error) {
        
    }];
}

@end
